import {
  disableWorkTime,
  getWeekLabel,
  weekNameList,
} from "@/pages/course/interface";
import { disabledDate } from "@/utils/common";
import Https from "@/utils/Https";
import {
  PageContainer,
  ProForm,
  ProFormText,
} from "@ant-design/pro-components";
import {
  Select,
  Spin,
  message,
  DatePicker,
  Tabs,
  Empty,
  Modal,
  Form,
  TimePicker,
  Space,
  Button,
  Popconfirm,
} from "antd";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import styles from "./styles.less";
import RoomCourse from "./Component/roomCourse";
import TextArea from "antd/es/input/TextArea";
import { history } from "umi";
import { FullscreenExitOutlined, FullscreenOutlined } from "@ant-design/icons";
const ClassRoomOccupy: React.FC<{}> = (props) => {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [sortReload, setSortReload] = useState(false);
  //场馆列表
  const [venueList, setVenueList] = useState([]);
  //场馆信息
  const [venueObj, setVenueObj] = useState({});
  const [weekTimeList, setWeekTimeList] = useState([]);
  const [weekTimeInfo, setWeekTimeInfo] = useState({});
  const [defaultWeekValue, setDefaultWeekValue] = useState<any>("");
  //运营时间
  const [venueHours, setVenueHours] = useState({});
  const [title, setTitle] = useState("");
  const [activeKey, setActiveKey] = useState("");
  const [full, setFull] = useState(false);
  const formRef = useRef();
  //禁用时间区间
  const { disabledHours, disabledMinutes } = disableWorkTime(
    dayjs(venueHours.venueStart, "HH:mm"),
    dayjs(venueHours.venueEnd, "HH:mm"),
    15
  );
  //获取所有场馆
  const getAllVenue = async () => {
    setLoading(true);
    let res: any = await Https.get("/venue/info/queryVenueTradeHour", {}, true);
    if (res.code == 200 && res.data) {
      setVenueObj(res.data);
    } else {
      message.error(res.msg);
    }
    setLoading(false);
  };
  //获取本周日期排序
  const getWeekList = async (id, defaultWeekValue) => {
    let params = {
      weekType: "2",
      pramDate: dayjs(defaultWeekValue).format("YYYY-MM-DD"),
      venueId: id,
    };
    setLoading(true);
    let res: any = await Https.post("/course/sched/timeWeek", params, true);
    if (res.code == 200) {
      let objList: any = [];
      if (res.data.length > 0) {
        res.data.map((item) => {
          objList.push({
            ...item,
            label: getWeekLabel(item.date),
            key: item.date,
          });
        });
        setWeekTimeInfo(objList[0]);
        setActiveKey(objList[0].key);
        setWeekTimeList(objList);
      } else {
        setWeekTimeList([]);
      }
    } else {
      setWeekTimeList([]);
      message.error(res.msg);
    }
    setLoading(false);
  };
  //删除记录
  const deleteItem = async (ids) => {
    setLoading(true);
    let res = await Https.post("/classRoomOccupancy/delete", ids, true);
    setLoading(false);
    if (res.code == 200) {
      message.success("操作成功");
      setSortReload(!sortReload);
      setOpen(false);
    } else {
      message.error(res.msg);
    }
  };
  //保存占用记录
  const save = async () => {
    let result = await formRef?.current?.validateFields();
    let params = {
      id: result.id ? result.id : null,
      occupiedType: 4,
      classRoomId: result.classRoomId,
      startTimeSlot:
        weekTimeInfo.date + " " + dayjs(result.time[0]).format("HH:mm:ss"),
      endTimeSlot:
        weekTimeInfo.date + " " + dayjs(result.time[1]).format("HH:mm:ss"),
      remark: result.remark,
    };
    let url = result.id
      ? "/classRoomOccupancy/update"
      : "/classRoomOccupancy/save";
    let methods = result.id ? "put" : "post";
    setLoading(true);
    let res = await Https[methods](url, params, true);
    setLoading(false);
    if (res.code == 200) {
      message.success("操作成功");
      setSortReload(!sortReload);
      setOpen(false);
    } else {
      message.error(res.msg);
    }
  };
  useEffect(() => {
    getAllVenue();
    setDefaultWeekValue(dayjs());
  }, []);
  useEffect(() => {
    if (venueObj.id && defaultWeekValue) {
      getWeekList(venueObj.id, defaultWeekValue);
    }
    setWeekTimeInfo({});
  }, [venueObj, defaultWeekValue]);
  return (
    <div className={full ? styles.FullContainer : ""}>
      <Spin spinning={loading}>
        <PageContainer
          onBack={() => {
            history.push("/stadium/classroom");
          }}
          title="教室时间占用表"
          className={styles.ClassRoomOccupy}
        >
          <div>
            {/* <Select
              placeholder="请选择场馆"
              style={{ width: "200px" }}
              value={venueObj.id}
              onChange={(val) => {
                let obj = venueList.filter(function (o) {
                  return o.id == val;
                })[0];
                setVenueObj(obj);
              }}
            >
              {venueList &&
                venueList.map((item, index) => (
                  <Select.Option key={item.id} value={item.id}>
                    {item.venueName}
                  </Select.Option>
                ))}
            </Select> */}
            <DatePicker
              style={{ marginLeft: "20px", width: "200px" }}
              format={`YYYY-MM-DD 第wo`}
              allowClear={false}
              picker="week"
              value={defaultWeekValue}
              disabledDate={disabledDate}
              renderExtraFooter={() => {
                return (
                  <div style={{ width: "100%", textAlign: "center" }}>
                    <a
                      onClick={() => {
                        setDefaultWeekValue(dayjs());
                      }}
                    >
                      回到今天
                    </a>
                  </div>
                );
              }}
              onChange={(date) => {
                setDefaultWeekValue(date);
              }}
            />
          </div>
          <div className={styles.content}>
            {!venueObj.id ? (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={
                  <div>
                    暂无场馆数据 <br /> 请
                    <a
                      onClick={() => {
                        getAllVenue();
                      }}
                    >
                      刷新
                    </a>
                    重试
                  </div>
                }
              />
            ) : (
              <div id="FullBox" className={full ? styles.tabFixed : ""}>
                <div className={styles.tabFlex}>
                  <Tabs
                    onChange={(val) => {
                      let obj = weekTimeList.filter(function (o) {
                        return o.date == val;
                      })[0];
                      setActiveKey(val);
                      setWeekTimeInfo(obj);
                    }}
                    type="card"
                    activeKey={activeKey}
                    items={weekTimeList}
                  />
                  <div className={styles.FullIcon}>
                    {full ? (
                      <FullscreenExitOutlined
                        title="取消全屏"
                        onClick={() => {
                          setFull(!full);
                        }}
                      />
                    ) : (
                      <FullscreenOutlined
                        title="全屏"
                        onClick={() => {
                          setFull(!full);
                        }}
                      />
                    )}
                  </div>
                </div>
                <RoomCourse
                  weekTimeInfo={weekTimeInfo}
                  venueObj={venueObj}
                  sortReload={sortReload}
                  isFull={full}
                  addWork={(type, info, title) => {
                    let getHourse = JSON.parse(venueObj.venueTradeHours);
                    let index =
                      dayjs(weekTimeInfo.date).day() == 0
                        ? 7
                        : dayjs(weekTimeInfo.date).day();
                    let venueTime = getHourse.filter(function (o) {
                      return o.days.indexOf(index) > -1;
                    });
                    if (venueTime.length == 0) {
                      message.error("该场馆下当天没有运营时间");
                    } else {
                      let venueStart = venueTime[0].time.split("-")[0];
                      let venueEnd = venueTime[0].time.split("-")[1];
                      setVenueHours({ venueStart, venueEnd });
                      setOpen(true);
                      setTitle(title);
                      setLoading(true);
                      formRef?.current?.resetFields();
                      setTimeout(() => {
                        if (type == "add") {
                          formRef?.current?.setFieldsValue({
                            classRoomName: info.classRoomName,
                            classDate:
                              dayjs(weekTimeInfo.date).format("YYYY-MM-DD") +
                              "(" +
                              weekNameList[
                                dayjs(weekTimeInfo.date).day() == 0
                                  ? 7
                                  : dayjs(weekTimeInfo.date).day()
                              ] +
                              ")",
                            classRoomId: info.classRoomId,
                          });
                        } else {
                          formRef?.current?.setFieldsValue({
                            id: info.id,
                            classRoomId: info.classRoomId,
                            classRoomName: info.classRoomName,
                            classDate:
                              dayjs(info.startTimeSlot).format("YYYY-MM-DD") +
                              "(" +
                              weekNameList[
                                dayjs(info.startTimeSlot).day() == 0
                                  ? 7
                                  : dayjs(info.startTimeSlot).day()
                              ] +
                              ")",
                            time: [
                              dayjs(info.startTimeSlot),
                              dayjs(info.endTimeSlot),
                            ],
                            remark: info.remark,
                          });
                        }
                        setLoading(false);
                      }, 500);
                    }
                  }}
                />
              </div>
            )}
          </div>
          <Modal
            title={title}
            open={open}
            width="40%"
            onCancel={() => {
              setOpen(false);
            }}
            footer={
              <Space>
                <Button
                  onClick={() => {
                    setOpen(false);
                  }}
                >
                  取消
                </Button>
                {title == "编辑占用" && (
                  <Popconfirm
                    title="是否删除这条记录?"
                    onConfirm={() => {
                      let id = formRef?.current?.getFieldFormatValue("id");
                      deleteItem([id]);
                    }}
                  >
                    <Button danger>删除</Button>
                  </Popconfirm>
                )}
                <Button
                  type="primary"
                  onClick={() => {
                    save();
                  }}
                  loading={loading}
                >
                  确定
                </Button>
              </Space>
            }
          >
            <Spin spinning={loading}>
              <ProForm
                formRef={formRef}
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 16 }}
                submitter={false}
                layout="horizontal"
              >
                <Form.Item label="id" name="id" hidden></Form.Item>
                <Form.Item
                  label="classRoomId"
                  name="classRoomId"
                  hidden
                ></Form.Item>
                <ProFormText name="classRoomName" label="教室名" readonly />
                <ProFormText name="classDate" label="占用日期" readonly />
                <Form.Item
                  label="占用时间"
                  name="time"
                  rules={[
                    {
                      required: true,
                      message: "请选择占用时间",
                    },
                  ]}
                >
                  <TimePicker.RangePicker
                    format={"HH:mm"}
                    minuteStep={15}
                    disabledHours={disabledHours}
                    disabledMinutes={disabledMinutes}
                    allowClear={false}
                    getPopupContainer={(triggerNode) =>
                      triggerNode.parentElement
                    }
                  />
                </Form.Item>
                <Form.Item
                  label="占用原因"
                  name="remark"
                  rules={[
                    {
                      required: true,
                      message: "请输入占用原因",
                    },
                    {
                      pattern: /^(?=.*\S).+$/,
                      message: "请输入正确的格式,不能全部是空格",
                    },
                  ]}
                >
                  <TextArea
                    placeholder="请输入占用原因"
                    maxLength={300}
                    showCount
                    allowClear
                    style={{ height: "120px" }}
                  />
                </Form.Item>
              </ProForm>
            </Spin>
          </Modal>
        </PageContainer>
      </Spin>
    </div>
  );
};
export default ClassRoomOccupy;
